import { Point } from '../../utils/es6AddPoint'
import { createDraw } from '../../utils/createDraw'
import { useGlobalMap } from '../../plugins/globalmap'

export const useFormAddEvent = () => {
  let map = useGlobalMap()
  const eventFormShow = ref(false)
  const isAddEvent = ref(true)
  const alreadyAuditShow = ref(true)
  const form = reactive({
    eventId: 'SJ2023',
    eventDriver: '',
    eventType: '',
    eventLevel: '',
    eventTime: '',
    eventLocation: '',
    plateNumber: '',
    eventStatus: ''
  })

  // 实现添加添加事件\
  let docLayer, position, service, attr
  let draw = []
  const handleAddUserEvent = async (row) => {
    alreadyAuditShow.value = !alreadyAuditShow.value
    // 回显表单数据
    if (row.id) {
      getOneEventHttp(row.id).then((res) => {
        form.eventDriver = res.data.data.event_driver
        form.eventType = res.data.data.event_type
        form.eventTime = res.data.data.event_date
        form.eventLocation = res.data.data.road_section_id
        form.plateNumber = res.data.data.event_car_number
        addPoint()
      })
    } else {
      addPoint()
    }
    // 实现添加点

    function addPoint() {
      docLayer = map.getLayers().item(1)
      // 创建画布
      var source = new ol.source.Vector({})
      var layer = new ol.layer.Vector({
        source
      })
      map.addLayer(layer)
      // 绘制点
      map.removeInteraction(draw)
      draw = createDraw({
        type: 'Point',
        source
      })

      map.addInteraction(draw)
      draw.on('drawend', (e) => {
        eventFormShow.value = !eventFormShow.value
        position = e.feature.getGeometry().getCoordinates()
        service = {
          name: 'guanggu',
          layerId: 2
        }
        attr = [
          { type: 'string', key: '事件编号', value: form.eventId },
          { type: 'string', key: '事件类型', value: form.eventType },
          { type: 'smallint', key: '事件等级', value: form.eventLevel },
          { type: 'string', key: '发生时间', value: form.eventTime },
          { type: 'string', key: '发生地点', value: form.eventLocation },
          { type: 'string', key: '车牌号', value: form.plateNumber },
          { type: 'string', key: '驾驶员', value: form.eventStatus },
          { type: 'smallint', key: '处理状态', value: form.eventStatus }
        ]
      })
    }
  }

  // 提交事件添加
  const submitForm = () => {
    Point.add({
      position,
      service,
      attr,
      docLayer
    })
  }

  return {
    form,
    eventFormShow,
    isAddEvent,
    alreadyAuditShow,
    handleAddUserEvent,
    submitForm
  }
}
